package com.reggie.controller;

import com.reggie.common.R;
import com.reggie.pojo.AddressBook;
import com.reggie.service.impl.AddressBookServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
@Slf4j
public class AddressBookController {

    @Autowired
    private AddressBookServiceImpl addressBookService;

    @GetMapping("/list")
    public R<List<AddressBook>> selectAll() {
        return R.success(addressBookService.selectAll());
    }

    @PutMapping("/default")
    public R<String> updateDefault(@RequestBody AddressBook addressBook) {
        log.info("修改默认地址服务器");
        System.out.println(addressBook.getId());
        int i = addressBookService.updateDefault(addressBook.getId());
        if (i > 0) {
            return R.success("修改成功！");
        } else {
            return R.error("修改失败");
        }
    }

    @GetMapping("/default")
    public R<AddressBook> getAddress() {
        return R.success(addressBookService.getDefault());
    }

    @GetMapping("/{id}")
    public R<AddressBook> getAddressById(@PathVariable Long id) {
        return R.success(addressBookService.getAddressById(id));
    }

    @PutMapping
    public R<String> updateAddress(@RequestBody AddressBook addressBook) {
        Boolean flag = addressBookService.updateAddress(addressBook);
        return flag ? R.success("修改成功") : R.error("修改失败");

    }

    @PostMapping
    public R<String> addAddress(@RequestBody AddressBook addressBook, HttpServletRequest request){
        addressBook.setUserId((Long) request.getSession().getAttribute("user"));
        addressBookService.addAddress(addressBook);
        return R.success("添加成功！");
    }

    @DeleteMapping
    public R<String> deleteById(Long ids){
        int i = addressBookService.deleteById(ids);
        return i > 0? R.success("删除成功！") : R.error("删除失败！");
    }
}
